# encoding:utf8

import os
import sys
import hashlib
import string
import logging


def get_filemd5(filepath):
    ''' 获取文件md5 '''
    m5 = hashlib.md5()
    data = file(filepath, "rb")
    while True:
        b = data.read(1024)
        if not b:
            break
        m5.update(b)
    data.close()
    return m5.hexdigest()


def chk_resinfo(path, chktype):
    ''' 检测文件信息 '''
    if os.path.split(path)[1] != "res":
        print (os.path.split(path)[1], "---os.path.split(path)[1]")
        logging.error("Set the path to the res root path!")
        return
    
    infolist = []

    def txt_findson(sonpath):
        ''' 文本形式组织文件列表 '''
        fileobj = None
        for filename in os.listdir(sonpath):
            fileobj = os.path.join(sonpath, filename)
            if os.path.isdir(fileobj):
                txt_findson(fileobj)
            else:
                # md5
                md5 = get_filemd5(fileobj)

                infostr = ""
                tmp = "res" + string.split(fileobj, "res")[1] + "|"
                infostr += string.replace(tmp, "\\", "/")
                infostr += md5 + "|"
                infostr += str(os.path.getsize(fileobj))
                infolist.append(infostr)

    def json_findson(sonpath):
        ''' json形式组织文件列表 '''
        fileobj = None
        for filename in os.listdir(sonpath):
            fileobj = os.path.join(sonpath, filename)
            if os.path.isdir(fileobj):
                json_findson(fileobj)
            else:
                # md5
                # tmp = string.split(fileobj, "res")
                tmp = fileobj.replace(path, "")
                res = string.replace(tmp, "\\", "/")
                infodic = dict()
                infodic["md5"] = get_filemd5(fileobj)
                infodic["size"] = str(os.path.getsize(fileobj))
                infodic["name"] = "res" + res
                infolist.append(infodic)

    if chktype == "txt":
        txt_findson(path)
    elif chktype == "json":
        json_findson(path)
    return infolist
